<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew :title="title" :breadCrumb="breadCrumb" showBack>
      </pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-input-search
          @press-enter="search"
          @search="search"
          :style="{ width: '320px' }"
          placeholder="请输入模板名称"
          search-button
          v-model="params.name"
        />
      </template>
      <template #right>
        <a-button @click="add" type="primary">新增模板</a-button>
      </template>
    </ConditionBox>
    <table-turn :table-data="tableData" ref="tableRef">
      <a-table-column align="center" :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        :width="200"
        dataIndex="name"
        align="center"
        title="模板名称"
      ></a-table-column>
      <a-table-column
        :width="200"
        dataIndex="remark"
        align="center"
        title="模板描述"
      ></a-table-column>
      <a-table-column
        :width="200"
        align="center"
        dataIndex="enable"
        title="模板状态"
      >
        <template #cell="{ record }">
          <a-tag
            class="enable"
            :color="
              record.enable === 1
                ? `rgb(var(--green-1))`
                : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))',
              '--enable':
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))'
            }"
          >
            {{ record.enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column
        :width="200"
        align="center"
        dataIndex="isShowDefault"
        title="设为默认"
      >
        <template #cell="{ record }">
          <a-switch
            @change="changeRequired(record)"
            :checked-value="1"
            :unchecked-value="2"
            v-model="record.isShowDefault"
          />
          <!-- {{ record.required === 2 ? '禁用' : '启用' }} -->
        </template>
      </a-table-column>
      <a-table-column title="操作" align="center" :width="120" fixed="right">
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="预览">
              <icon-eye
                size="26"
                @click="look(record, 2)"
                style="color: #5085ff; cursor: pointer"
              />
            </a-tooltip>
            <a-tooltip content="复制">
              <IconFont
                type="icon-fuzhi"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goCopy(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <icon-font
                type="icon-edit"
                :size="26"
                @click="goEdit(record)"
                :style="{
                  cursor: 'pointer'
                }"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm content="是否确认删除该条数据?" @ok="del(record)">
                <icon-font
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </table-turn>
  </ContentCard>

  <TemplateDesign
    type="editShow"
    title="入职手续模板"
    ref="showTemplate"
    :id="fromData.data.id"
    @saveForm="saveForm"
    :back="back"
    :template="templateDataShow"
    :hierarchy="1"
    @upshowData="upshowData"
    @sortshowData="sortshowData"
    :refForm="refForm"
  >
    <!-- @saveForm="saveForm" -->
    <template #base>
      <a-form
        ref="refForm"
        :model="fromData.data"
        layout="vertical"
        :rules="rules"
      >
        <a-form-item field="name" label="入职手续名称" required>
          <a-input
            size="large"
            v-model="fromData.data.name"
            placeholder="请输入模板名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="enable" label="启用状态">
          <a-switch
            v-model="fromData.data.enable"
            :checked-value="1"
            :unchecked-value="2"
          />
        </a-form-item>
        <a-form-item field="remark" label="描述">
          <a-textarea
            v-model="fromData.data.remark"
            placeholder="请输入"
            show-word-limit
            :max-length="300"
            :auto-size="{
              minRows: 5
            }"
            allow-clear
          />
        </a-form-item>
      </a-form>
    </template>
    <template #template-design>
      <div class="business">
        <div class="subDetail">
          <div class="head">
            <div class="sub-title">
              <p class="icon"></p>
              入职手续清单
            </div>
          </div>
          <div style="width: 100%; margin: auto">
            <a-table
              :data="procedure.list"
              :span-method="dataSpanMethod"
              :bordered="{
                wrapper: true,
                cell: true,
                headerCell: true,
                bodyCell: true
              }"
              stripe
              :pagination="false"
            >
              <template #columns>
                <a-table-column
                  align="center"
                  title="办理环节"
                  dataIndex="handlerProcess"
                  :width="200"
                >
                </a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="handlerMatters"
                  align="center"
                  title="办理事项"
                ></a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="matterAsk"
                  align="center"
                  title="办理事项要求"
                ></a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="handlerDept"
                  align="center"
                  title="办理部门"
                >
                  <template #cell="{ record }">
                    {{
                      departmentSelectData.data.filter(
                        (ele: any) => ele.id === record.handlerDept
                      )[0]?.name
                    }}
                  </template>
                </a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="handlerUser"
                  align="center"
                  title="办理人"
                >
                  <template #cell="{ record }">
                    {{ getRoster(record.handlerUser) }}
                  </template>
                </a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="userMobile"
                  align="center"
                  title="办理人联系方式"
                >
                  <template #cell="{ record }">
                    {{ record.userMobile || '自动获取' }}
                  </template>
                </a-table-column>

                <a-table-column
                  :width="200"
                  dataIndex="handlerAddr"
                  align="center"
                  title="办理地点"
                >
                  <template #cell="{ record }">
                    {{
                      locationSelectData.data.filter(
                        (ele: any) => ele.id === record.handlerAddr
                      )[0]?.name
                    }}
                  </template>
                </a-table-column>
                <a-table-column
                  title="操作"
                  dataIndex="operation"
                  align="center"
                  :width="120"
                  fixed="right"
                >
                  <template #cell="{ record }">
                    <a-tooltip content="编辑">
                      <icon-font
                        @click="editDetails(record)"
                        type="icon-edit"
                        :size="26"
                        :style="{
                          marginRight: '10px',
                          cursor: 'pointer'
                        }"
                      />
                    </a-tooltip>
                    <a-tooltip content="删除" position="left">
                      <a-popconfirm
                        content="是否确认删除该条数据?"
                        @ok="delDetails(record)"
                      >
                        <icon-font
                          type="icon-delete"
                          :size="26"
                          :style="{
                            cursor: 'pointer',
                            marginRight: '10px'
                          }"
                        />
                      </a-popconfirm>
                    </a-tooltip>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </div>
          <div
            @click="addList"
            style="padding: 20px; color: #3d7eff; cursor: pointer"
          >
            <icon-plus /> 新增入职手续清单
          </div>
        </div>
      </div>
    </template>
  </TemplateDesign>

  <eventFrom
    @updateFromData="updateFromData"
    @updateFromDataOne="updateFromDataOne"
    v-model:visible="visibleEvent"
    :fromData="editfromData"
    :allNode="allNode"
  />
  <!-- // 预览 -->
  <a-modal
    :width="1200"
    v-model:visible="lookShow"
    ok-text="关闭"
    :hide-cancel="true"
  >
    <template #title> {{ lookData.data?.name }} </template>
    <div>
      <div class="business">
        <div class="subDetail">
          <div class="head">
            <div class="sub-title">
              <p class="icon"></p>
              基础信息
            </div>
          </div>
        </div>
        <div style="width: 90%; margin: auto">
          <div class="cn">
            <div
              class="cn-main"
              v-for="ele in templateDataShow"
              :key="ele.ctlCode"
            >
              <span>{{
                ele.ctlCnName ? ele.ctlCnName : ele.cnName + ':'
              }}</span>
              <a-input class="cn-input" disabled placeholder="自动获取" />
            </div>
          </div>
        </div>
      </div>
      <div class="business">
        <div class="subDetail">
          <div class="head">
            <div class="sub-title">
              <p class="icon"></p>
              基础信息
            </div>
          </div>
        </div>
        <div style="width: 100%; margin: auto">
          <a-table
            :width="1200"
            :data="procedure.list"
            :span-method="dataSpanMethod"
            :pagination="false"
            :bordered="{
              wrapper: true,
              cell: true,
              headerCell: true,
              bodyCell: true
            }"
            stripe
          >
            <template #columns>
              <a-table-column
                align="center"
                title="办理环节"
                dataIndex="handlerProcess"
                :width="150"
              >
              </a-table-column>
              <a-table-column
                :width="150"
                dataIndex="handlerMatters"
                align="center"
                title="办理事项"
              ></a-table-column>
              <a-table-column
                :width="150"
                dataIndex="matterAsk"
                align="center"
                title="办理事项要求"
              ></a-table-column>
              <a-table-column
                :width="150"
                dataIndex="handlerDept"
                align="center"
                title="办理部门"
              >
                <template #cell="{ record }">
                  {{
                    departmentSelectData.data.filter(
                      (ele: any) => ele.id === record.handlerDept
                    )[0]?.name
                  }}
                </template>
              </a-table-column>
              <a-table-column
                :width="150"
                dataIndex="handlerUser"
                align="center"
                title="办理人"
              >
                <template #cell="{ record }">
                  {{ getRoster(record.handlerUser) }}
                </template>
              </a-table-column>
              <a-table-column
                :width="150"
                dataIndex="userMobile"
                align="center"
                title="办理人联系方式"
              >
                <template #cell="{ record }">
                  {{ record.userMobile || '自动获取' }}
                </template>
              </a-table-column>
              <a-table-column
                :width="150"
                dataIndex="handlerAddr"
                align="center"
                title="办理地点"
              >
                <template #cell="{ record }">
                  {{
                    locationSelectData.data.filter(
                      (ele: any) => ele.id === record.handlerAddr
                    )[0]?.name
                  }}
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </a-modal>

  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
  />
</template>
<script setup lang="ts">
import {
  GetOnboardingProcedure,
  DelOnboardingProcedure,
  GetOnboardingProcedureById,
  EditOnboardingProcedureDefault,
  PutOnboardingProceduretemplate,
  AddOnboardingProcedure,
  DelOnboardingProcedureDetails,
  AddOnboardingProcedureDetails,
  EditOnboardingProcedure,
  RepeatOnboardingProcedure,
  GetProcedureList,
  PutOnboardingProcedureDetails,
  DelProcedure,
  EditOnboardingProcedureStatus
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement';
import { GetWorkPlaceList } from '@/apis/management/organization/organizationManagement';
import { changeControlData } from '@/utils/control';
import { GetBusinessModalData } from '@/apis/controltotal/index';
import { Message } from '@arco-design/web-vue';
import eventFrom from './formalitiesTemplate/fromSetting/eventFrom';
import clonedeep from 'lodash.clonedeep';
import { GetHumanRosterList } from '@/apis/management/human/humanRoster';
import { findLastIndex } from 'lodash';
import { flatTree, dataTreeFilter, downloadExcelFile } from '@/utils/utils';

const title = '入职手续模板列表';
const breadCrumb: string[] = ['人事', '基础设置', '入职手续模板设置'];
let showTemplate = ref(); // Template显示
const params = reactive({ name: '', ownerType: 2 });
const data = ref({});
const visibleEvent = ref(false);
const editfromData: any = ref({});
const fromData = reactive<any>({
  data: {
    id: null,
    ownerType: 2, //1工作交接 2入职手续 3 离职手续
    name: '',
    enable: 1,
    remark: '',
    isShowDefault: 2,
    controls: [],
    details: []
  }
});
const refForm = ref();
// 搜索
const search = () => {
  tableRef.value.loadData();
};
const lookShow = ref(false);
// 删除
//@typescript-eslint/no-explicit-any
const del = async (data: any) => {
  try {
    if (data.isShowDefault === 1) {
      return Message.error('默认模板无法删除');
    }
    await DelOnboardingProcedure({ id: data.id });
    tableRef.value.loadData();
    await DelProcedure({ ids: [data.id], delType: 1 });
  } catch (error) {
    console.log(error);
  }
};
const tableRef = ref();
const tableData = async (page: any) => {
  try {
    const res: any = await GetOnboardingProcedure({
      ...page,
      name: params.name,
      ownerType: params.ownerType
    });
    return Promise.resolve(res);
  } catch (err: unknown) {
    console.log(err);
  }
};
const templateData: any = reactive({ data: [] });
const allNode = computed(() => {
  const data: string[] = [];
  fromData.data.details?.forEach((ele: any) => {
    data.push(ele.node);
  });
  return data;
});

const init = async () => {
  const res = await GetBusinessModalData({
    funcCode: 'SER_FUNC479B4EA261AF4A9B8B160389128570ED'
  });
  initData.data = res?.funcCtlInfos;
  templateData.data = res?.funcCtlInfos
    ? changeControlData(res.funcCtlInfos, 'tableHead')
    : null;
};
init();
// 控件显示数据
const templateDataShow = computed(() => {
  if (fromData.data.controls?.length === 0) {
    templateData.data?.forEach((ele: any) => {
      ele.show = true;
    });
    return templateData.data;
  } else {
    const data = clonedeep(templateData.data);
    const ids: string[] = [];
    const subId: number[] = [];
    const idsShow: { show: number; id: number }[] = [];
    fromData.data.controls?.forEach((ele: any) => {
      ids.push(ele.ctlCode + ele.subsetId);
      idsShow.push({ id: ele.id, show: ele.show });
    });
    data.forEach((ele: any, index: number) => {
      if (ids.indexOf(ele.ctlCode + ele.subsetId) !== -1) {
        ele.show =
          idsShow[ids.indexOf(ele.ctlCode + ele.subsetId)].show === 1
            ? true
            : false;
        ele.id = idsShow[ids.indexOf(ele.ctlCode + ele.subsetId)].id;
      }
    });
    return data;
  }
});
const initData: any = reactive({ data: {} });
// 表格合并
const dataSpanMethod = (datas: any) => {
  const { record, rowIndex, columnIndex, column } = datas;
  // 当检索到相同数据则返回 那条数据
  let arr = procedure.list.filter((res: any) => {
    return res.handlerProcess == record.handlerProcess;
  });
  // 匹配到相同数据的长度
  // obj.rowspan = arr.length;
  if (
    procedure.list[rowIndex - 1]?.handlerProcess != record.handlerProcess &&
    (column.dataIndex === 'handlerProcess' ||
      column.dataIndex === 'handlerDept' ||
      column.dataIndex === 'handlerUser' ||
      column.dataIndex === 'handlerAddr' ||
      column.dataIndex === 'userMobile' ||
      column.dataIndex === 'operation' ||
      column.dataIndex === 'personName')
  ) {
    // 匹配到相同数据的长度
    return { rowspan: arr.length };
  }
};
// 修改状态
const changeStatus = async (data: any) => {
  await EditOnboardingProcedureStatus({
    ids: [data.id],
    enable: data.enable
  });
  tableRef.value.loadData();
};
// 修改默认
const changeRequired = async (data: any) => {
  await EditOnboardingProcedureDefault({
    id: data.id,
    ownerType: 2
  });
  tableRef.value.loadData();
};
// 点击新增模板按钮
const add = () => {
  //
  showTemplate.value.fullScreen();
};
const procedure = reactive<{ list: any[] }>({ list: [] });
// 编辑
const goEdit = async (record: any, name?: string) => {
  //获取基础信息
  const res = await GetOnboardingProcedureById({ id: record.id });
  fromData.data = res;
  // fromData.data.name = name;
  // 获取表单设计
  const resp = await GetProcedureList({
    ownerId: record.id,
    ownerType: 2
  });

  procedure.list = resp.proceduresList || [];
  //  procedure.list.sort((a: any, b: any) =>
  //    a.handlerProcess.localeCompare(b.handlerProcess)
  //  );
  // procedure.list.forEach((item: any) => {
  //   item.demands = [
  //     {
  //       id: item.id,
  //       handlerMatters: item.handlerMatters,
  //       matterAsk: item.matterAsk
  //     }
  //   ];
  // });
  rulesEdit.data.name = res.name;
  rulesEdit.data.edit = true;
  showTemplate.value.fullScreen();
  //
};
const addList = () => {
  visibleEvent.value = true;
  editfromData.value = {
    ownerId: fromData.data.id,
    ownerType: 2,
    demands: [{ handlerMatters: '', matterAsk: '' }]
  };
};
// 保存基础设置
const save = async () => {
  if (fromData.data.name === '') {
    Message.error('模板名不能为空');
    return 2;
  }

  if (fromData.data.id) {
    await EditOnboardingProcedure({ level: 1, template: fromData.data });
  } else {
    fromData.data.controls = clonedeep(templateData.data);
    fromData.data.controls.forEach((ele: any) => {
      ele.show ? (ele.show = 1) : (ele.show = 2);
    });
    const id = await AddOnboardingProcedure({
      level: 1,
      template: fromData.data
    });
    let collection = {
      templateId: id,
      cnName: initData.data.name
    };
    const collectionId = await AddOnboardingProcedure({
      level: 2,
      collection: collection
    });
    let control = fromData.data.controls.map((ele: any) => ({
      collectionId,
      ctlCnName: ele.cnName,
      ctlComponentType: ele.componentType,
      ctlCode: ele.ctlCode,
      ctlEnName: ele.enName,
      props: ele.props,
      ctlFieldName: ele.fieldName
    }));
    await AddOnboardingProcedure({
      level: 3,
      control
    });
    fromData.data.id = id;
  }
  tableRef.value.loadData();
  rulesEdit.data.name = '';
  rulesEdit.data.edit = false;
};
/**
 * 保存模板的表单设计
 */
const saveForm = async () => {
  await save();
  // 增删改
  procedure.list.forEach(async (item: any) => {
    if (!item.id) {
      item.ownerId = fromData.data.id;
      item.ownerType = 2;
      await AddOnboardingProcedureDetails(item);
      console.log('新增', item);
    } else {
      console.log('修改', item);
      await PutOnboardingProcedureDetails(item);
    }
  });
  if (delIds.value.length) {
    // console.log('删除', delIds.value);
    await DelProcedure({ ids: delIds.value, delType: 2 });
    delIds.value = [];
  }
  fromData.data = {};
};
// 取消
const back = () => {
  //
  fromData.data = {
    id: null,
    name: '',
    enable: 1,
    remark: '',
    controls: [],
    details: []
  };
  rulesEdit.data.name = '';
  rulesEdit.data.edit = false;
};
// 更新模板
const upshowData = async (e: any) => {
  //
  const pending: string[] = [];
  const pendingState: { id: string; show: boolean }[] = [];
  const ids: { id: number; show: number; hid: number }[] = [];
  e.forEach((ele: any) => {
    if (ele.id) ids.push({ id: ele.id, show: ele.show ? 1 : 2, hid: ele.hid });
    pending.push(ele.subsetId + ele.ctlCode);
    pendingState.push({ id: ele.subsetId + ele.ctlCode, show: ele.show });
  });
  templateData.data.forEach((ele: any) => {
    if (pending.indexOf(ele.subsetId + ele.ctlCode) !== -1) {
      ele.show = pendingState[pending.indexOf(ele.subsetId + ele.ctlCode)].show;
    }
  });
  if (ids.length !== 0) {
    fromData.data.controls.forEach((ele: any) => {
      if (pending.indexOf(ele.subsetId + ele.ctlCode) !== -1) {
        ele.show = pendingState[pending.indexOf(ele.subsetId + ele.ctlCode)]
          .show
          ? 1
          : 2;
      }
    });
    await PutOnboardingProceduretemplate({
      controls: ids
    });
  }
};
// 排序
const sortshowData = () => {
  //
};
const editDetails = (data: any) => {
  if (!procedure.list.length) return;
  // 找到所有环节相同的项
  const demands: any[] = [];
  procedure.list.forEach((item: any) => {
    if (item.handlerProcess === data.handlerProcess) {
      demands.push({
        id: item.id,
        handlerMatters: item.handlerMatters,
        matterAsk: item.matterAsk
      });
    }
  });
  const newData = clonedeep(data);
  newData.edit = true;
  newData.demands = demands;
  visibleEvent.value = true;
  data.hid = fromData.data.id;
  editfromData.value = newData;
};
// @typescript-eslint/no-explicit-any
const delDetails = async (data: any) => {
  // 找到所有环节相同的项
  procedure.list.forEach((item: any) => {
    if (item.id && item.handlerProcess === data.handlerProcess) {
      delIds.value.push(item.id);
    }
  });
  // 过滤删除项
  procedure.list = procedure.list.filter(
    (item: any) => item.handlerProcess !== data.handlerProcess
  );
};

//入职手续表单数据
const from = computed(() => {
  if (typeof procedure.list === 'object' && procedure.list.length) {
    const tempArr: any = [];
    procedure.list.forEach((ele: any) => {
      const index = tempArr.findIndex((item: any) => {
        return (
          item.handlerProcess === ele.handlerProcess &&
          item.handlerDept === ele.handlerDept &&
          item.handlerUser === ele.handlerUser &&
          item.handlerAddr === ele.handlerAddr
        );
      });
      if (index < 0) {
        tempArr.push;
      }
    });
  }
});
// @typescript-eslint/no-explicit-any
const updateFromData = async (e: any) => {
  if (typeof e.demands === 'object' && e.demands.length) {
    e.demands.forEach((item: any) => {
      const temp = Object.assign(item, e);
      procedure.list.push(temp);
    });
  }
  //  procedure.list.sort((a: any, b: any) =>
  //    a.handlerProcess.localeCompare(b.handlerProcess)
  //  );
};
const delIds = ref<number[]>([]);
const updateFromDataOne = async (e: any) => {
  procedure.list = procedure.list.filter(
    (item: any) =>
      item.handlerProcess !== editfromData.value.handlerProcess || item.id
  );

  if (typeof e.demands === 'object' && e.demands.length) {
    e.demands.forEach((item: any) => {
      if (!item.id) {
        const lastIndex = findLastIndex(
          procedure.list,
          (item: any) =>
            editfromData.value.handlerProcess === item.handlerProcess
        );
        //add
        item.ownerId = fromData.data.id;
        item.handlerProcess = e.handlerProcess;
        item.ownerType = 2;
        item.handlerDept = e.handlerDept;
        item.handlerUser = e.handlerUser;
        item.handlerAddr = e.handlerAddr;
        // procedure.list.push(item);
        console.log('item11', item);
        // procedure.list.splice(lastIndex + 1, 0, item);
        procedure.list.push(item);
        console.log('====================2222================');
        console.log(procedure.list);
        console.log('====================================');
      } else {
        //edit
        const node = procedure.list.find((ele: any) => ele.id === item.id);
        if (!node) return;
        node.handlerMatters = item.handlerMatters;
        node.matterAsk = item.matterAsk;
        node.handlerProcess = e.handlerProcess;
        node.handlerDept = e.handlerDept;
        node.handlerUser = e.handlerUser;
        node.handlerAddr = e.handlerAddr;
      }
    });
  }
  //delete

  editfromData.value.demands?.forEach((pro: any) => {
    const index = e.demands.findIndex((demand: any) => pro.id === demand.id);
    if (index >= 0) return;
    const procedureIndex = procedure.list.findIndex(
      (item: any) => pro.id === item.id
    );
    if (procedureIndex >= 0) {
      procedure.list.splice(procedureIndex, 1);
    }

    delIds.value.push(pro.id);
  });
  //  procedure.list.sort((a: any, b: any) =>
  //    a.handlerProcess.localeCompare(b.handlerProcess)
  //  );
};
const lookData: any = reactive({ data: { details: [] } });
// 预览
const look = async (oldData: any, type: number) => {
  const res = await GetOnboardingProcedureById({ id: oldData.id });
  const resp = await GetProcedureList({
    ownerId: oldData.id,
    ownerType: 2
  });
  procedure.list = resp.proceduresList || [];
  //  procedure.list.sort((a: any, b: any) =>
  //    a.handlerProcess.localeCompare(b.handlerProcess)
  //  );
  lookData.data = res;
  const newArr: any = [];
  lookData.data.details?.forEach((ele: any) => {
    if (ele.demands.length != 0) {
      ele.demands.forEach((item: any) => {
        item.node = ele.node;
        item.space = ele.space;
        item.department = ele.department;
        item.person = ele.person;
        item.phone = ele.phone;
        item.demands = clonedeep(ele.demands);
        newArr.push(clonedeep(item));
      });
    } else {
      newArr.push(
        clonedeep({
          node: ele.node,
          space: ele.space,
          department: ele.department,
          person: ele.person,
          phone: ele.phone
        })
      );
    }
  });

  // newArr?.forEach((item: any) => {
  //   return;
  //   item?.demands?.forEach(async (ele: any) => {
  //     console.log('ele.person', ele.person);
  //     const res = await GetHumanRosterDetail({ id: ele.person });
  //     item.personName
  //       ? null
  //       : (item.personName = res?.filter(
  //           (ele: any) => ele.code === 'C62B8DC31189847E0972B5D8F721404B1'
  //         )[0]?.value);
  //   });
  // });
  lookData.data.details = newArr;
  lookShow.value = true;
};
const departmentSelectData: any = reactive({ data: [] }); // 部门
const agentSelectData: any = reactive({
  data: []
}); // 办理人
const locationSelectData: any = reactive({ data: [] }); // 地点

const inits = async () => {
  const { content } = (await GetWorkPlaceList({
    pageNumber: 0,
    pageSize: -1
  })) as any;
  locationSelectData.data = content;
  const Getlist: any = await GetOrganizationList({});
  departmentSelectData.data = flatTree(Getlist);
  const list = await GetHumanRosterList({
    pageNumber: 0,
    pageSize: -1,
    typeName: '1,2,3,4,5,6,7,8,9,10,11,12'
  });
  agentSelectData.data = list.content;
  // const ids: number[] = [];
  // Getlist.forEach((ele: any) => {
  //   ele.controlData.forEach((item: any) => {
  //     item.code === 'C3D33FA57216F4968BDE51C31D623FC09' && item.value === '2'
  //       ? ids.push(ele.id)
  //       : null;
  //   });
  // });
  // Getlist.forEach((ele: any) => {
  //   if (ids.indexOf(ele.id) !== -1) {
  //     ele.controlData.forEach((item: any) => {
  //       item.code === 'C30BBF36A5AF541F7A2657671DEE2EDD6'
  //         ? departmentSelectData.data.push(item)
  //         : null;
  //     });
  //   }
  // });
};
const changeGetlistData = (data: any) => {
  let newData: any = [];
  for (const item of data) {
    if (typeof item.controlData !== 'object' || !item.controlData.length)
      return [];
    for (const items of item.controlData) {
      if (
        items.code === 'C3D33FA57216F4968BDE51C31D623FC09' &&
        items.value === '2'
      ) {
        newData.push({ id: item.id, value: item.name });
      }
    }
    if (item.children && item.children.length !== 0) {
      newData = newData.concat(changeGetlistData(item.children));
    }
  }
  return newData;
};
inits();

let copyVisible = ref(false);
let currId = ref(0);
// 显示复制弹窗
const goCopy = (id: number) => {
  currId.value = id;
  copyVisible.value = true;
};

// @typescript-eslint/no-unused-vars
const copyEmit = async (formData: any) => {
  const res: any = await GetOnboardingProcedureById({ id: currId.value });
  delete res.id;
  delete res.createdAt;
  res?.controls?.forEach((ele: any) => {
    delete ele.id;
  });
  res?.details?.forEach((ele: any) => {
    delete ele.id;
    delete ele.hid;
    ele?.demands?.forEach((item: any) => {
      delete item.id;
      delete item.did;
    });
  });
  res.isShowDefault = 2;
  res.name = formData.name;
  await AddOnboardingProcedure(res);
  tableRef.value.loadData();
};

// 复制弹窗点击确认并编辑
const copyEditEmit = (formData: any) => {
  goEdit(currId.value, formData.name);
};

const getRoster = (id: number) => {
  let s = '';
  s = agentSelectData.data?.filter((ele: any) => ele.id === id)[0]?.name;
  if (s) return s;
  return '未选择';
};

const rulesEdit = reactive({ data: { edit: false, name: '' } });
const validateName = async (name: string, cb: any) => {
  try {
    if (rulesEdit.data.edit && name === rulesEdit.data.name) {
      return;
    } else {
      const res = await RepeatOnboardingProcedure({
        name,
        ownerType: 2
      });
      if (res.code) cb(`${res.msg}`);
    }
  } catch (error: any) {
    console.log(error);
  }
};

const rules = {
  name: [
    {
      required: true,
      message: '请输入名称'
    },
    {
      validator: validateName
    }
  ]
};
</script>
<style lang="less" scoped>
.business {
  width: 90%;
  // height: 100%;
  // overflow: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: auto;
  margin-bottom: 20px;
  .subDetail {
    width: 100%;
    .head {
      box-sizing: border-box;
      border-radius: 4px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      padding: 10px;
      background-color: #e8f0ff;
      margin: 0 0 20px 0;
      .sub-title {
        display: flex;
        align-items: center;
        .icon {
          border-radius: 4px;
          width: 6px;
          height: 70%;
          background-color: #3d7eff;
          height: 20px;
          padding: 0;
          margin: 3px 0;
          margin-right: 10px;
        }
      }
      .setting {
        color: #3d7eff;
        cursor: pointer;
      }
    }
  }
}
.cn {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .cn-main {
    display: flex;
    width: 45%;
    margin-bottom: 20px;
    align-items: center;
    span {
      width: 100px;
      text-align: end;
      margin-right: 20px;
    }

    .cn-input {
      flex: 1;
    }
  }
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
